package com.nicky.kids.Utility;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;

import java.io.File;
import java.util.List;

/**
 * Created by NickZhang on 9/11/13.
 */
public class IntentUtil {
    private static final String TAG = "nick_IntentUtil";

    public static boolean hasActivityResolver(Context context, Intent intent) {
        if (intent == null) {
            return false;
        }
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> activities = pm.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY);
        return !activities.isEmpty();
    }

    public static void startIntent(Context context, Intent it) {
        if (it != null && hasActivityResolver(context, it)) {
            try {
                it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(it);
            } catch (ActivityNotFoundException e) {
                e.printStackTrace();
                TLog.e(TAG, "ActivityNotFoundException");
            } catch (SecurityException e) {
                e.printStackTrace();
                TLog.e(TAG, "SecurityException");
            }
        }
    }

    public static Intent getShareIntent(String subject, String content, String attachFile) {
        Intent it = new Intent(Intent.ACTION_SEND);
        if (!TextUtils.isEmpty(subject)) {
            it.putExtra(Intent.EXTRA_SUBJECT, subject);
        }
        if (!TextUtils.isEmpty(content)) {
            it.putExtra(Intent.EXTRA_TEXT, content);
        }
        if (!TextUtils.isEmpty(attachFile)) {
            Uri uri = Uri.fromFile(new File(Environment.getExternalStorageDirectory(), attachFile));
            it.putExtra(Intent.EXTRA_STREAM, uri);
        }
        it.setType("text/plain");
        return Intent.createChooser(it, "分享");
    }
}